package com.ptrsystem.siatd.dao.implementacion;

import com.ptrsystem.siatd.beans.Ubigeo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author uotu
 */
@Repository
public class MantenimientoUbigeoImplement implements com.ptrsystem.siatd.dao.interfaces.MantenimientoUbigeoInterface {

    @Autowired
    private DataSource dataSource;

    @Override
    @Transactional
    public boolean getRegistraUbigeo(Ubigeo ubi) {
        boolean rt = false;
        JdbcTemplate jdbc = new JdbcTemplate(this.dataSource);
        int rs = jdbc.update("INSERT INTO TD_UBIGEO VALUES(?,?,?,?,?,?,?,?,?)",
                ubi.getCodUbigeo(),
                ubi.getCodDpto(),
                ubi.getCodProv(),
                ubi.getCodDist(),
                ubi.getCodOtro(),
                ubi.getNomDpto(),
                ubi.getNomProv(),
                ubi.getNomDist(),
                ubi.getNomOtro()
        );
        if (rs > 0) {
            rt = !rt;
        }
        return rt;
    }

    @Override
    public List<Ubigeo> getListaUbigeo(String dep, String pro, String dis, String otr) {
        JdbcTemplate jdbc = new JdbcTemplate(this.dataSource);
        List<Ubigeo> lista = jdbc.query("select top(20) * from TD_UBIGEO where NOM_DEP like(?) and NOM_PROV like(?) and NOM_DIST like(?) and NOM_OTRO like(?);", new Object[]{"%" + dep + "%", "%" + pro + "%", "%" + dis + "%", "%" + otr + "%"}, new rowMapper());
        return lista;
    }

    private class rowMapper implements RowMapper<Ubigeo> {

        @Override
        public Ubigeo mapRow(ResultSet rs, int i) throws SQLException {
            Ubigeo ubigeo = new Ubigeo(rs.getString(1),
                    rs.getString(2),
                    rs.getString(3),
                    rs.getString(4),
                    rs.getString(5),
                    rs.getString(6),
                    rs.getString(7),
                    rs.getString(8),
                    rs.getString(9));
            return ubigeo;
        }

    }

}
